<?php
declare (strict_types = 1);

namespace app\common\model;

use think\Model;
use think\model\concern\SoftDelete;
use think\facade\Db;

class H5Server extends Model
{
    use SoftDelete;
     protected $deleteTime = false;
    // 获取列表
    public static function getList()
    {
        $where = [];
        $limit = input('get.limit');
        
               //按服务器ID查找
               if ($sid = input("sid")) {
                   $where[] = ["sid", "like", "%" . $sid . "%"];
               }
               //按服务器名查找
               if ($name = input("name")) {
                   $where[] = ["name", "like", "%" . $name . "%"];
               }
               //按服务器状态查找
               if ($status = input("status")) {
                   $where[] = ["status", "like", "%" . $status . "%"];
               }
               //按服务器IP查找
               if ($host = input("host")) {
                   $where[] = ["host", "like", "%" . $host . "%"];
               }
               //按服务器端口查找
               if ($port = input("port")) {
                   $where[] = ["port", "like", "%" . $port . "%"];
               }

        // 使用子查询来按sid分组并选择每组的第一条记录
        $subQuery = Db::table('h5.h5_server')
            ->field('min(id) as min_id')  // 每个sid分组中最小的id
            ->group('sid')
            ->buildSql();

        $query = Db::table('h5.h5_server')
            ->alias('s')
            ->join([$subQuery => 't'], 's.id = t.min_id')
            ->field('s.id, s.sid, s.name, s.status, s.host, s.port')  // 指定要选择的字段
            ->order('s.sid', 'asc')
            ->where($where);

        // 分页查询结果
        $list = $query->paginate($limit);
//        $list = Db::table('h5.h5_server')->order('sid','asc')->where($where)->paginate($limit);

        return ['code'=>0,'data'=>$list->items(),'extend'=>['count' => $list->total(), 'limit' => $limit]];
    }



    // 修改服务器状态
    public static function MoServerStatus($ids,$status)
    {
        $sql = "update h5.h5_server set `status`=$status where id in (".implode(',', $ids).")";
        Db::execute($sql);
    }
}
